<template>
  <div ref="barChart" :style="{ width, height }"></div>
</template>
<script setup lang="ts">
import useChart from "@/hooks/useChart"
import type { EChartsOption } from 'echarts'
import { ref, watch } from "vue"

interface IChartData {
  name: string,
  value: number
}
const props = defineProps({
  width: {
    type: String,
    default: '100%'
  },
  height: {
    type: String,
    default: '100%'
  },
  barDatas: {
    type: Array<IChartData>,
    default: () => []
  }
})

const barChart = ref()

const { setChartOption } = useChart(barChart, getOptions(props.barDatas))

watch(() => props.barDatas, () => {
  setChartOption(getOptions(props.barDatas))
})

function getOptions(data: IChartData[] = []) {
  const options: EChartsOption = {
    // backgroundColor: 'rbg(40,46,72)',
    grid: {
      left: "5%",
      right: "8%",
      top: "25%",
      bottom: "8%",
      containLabel: true, // grid 区域是否包含坐标轴的刻度标签
    },
    tooltip: {},
    xAxis: {
      axisLine: {
        show: true,
        lineStyle: {
          color: "#42A4FF",
        },
      },
      axisTick: {
        show: false,
      },
      axisLabel: {
        color: "white",
      },

      data: data.map(item => item.name),
    },
    yAxis: {
      name: "个",
      nameTextStyle: {
        color: "white",
        fontSize: 13,
      },
      axisLine: {
        show: true,
        lineStyle: {
          color: "#42A4FF",
        },
      },
      axisTick: {
        show: false,
      },
      splitLine: {
        show: true,
        lineStyle: {
          color: "#42A4FF",
        },
      },
      axisLabel: {
        color: "white",
      },
    },
    series: [
      {
        name: "销量",
        type: "bar",
        barWidth: 17,
        itemStyle: {
          color: {
            type: "linear",
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {
                offset: 0,
                color: "#01B1FF", // 0% 处的颜色
              },
              {
                offset: 1,
                color: "#033BFF", // 100% 处的颜色
              },
            ],
            global: false, // 缺省为 false
          },
        },
        data,
      },
    ],
  };
  return options
}

</script>